/**
 * 公共选择组织机构插件
 * @author lee
 */
var DepartDialog = function(opt) {
    //默认配置参数
    this.opt = {
    	url:"/common/asset/getDepartGroup",
    	params:{
    		state:1,//1 显示所有 2显示自己的组织机构
    		chooseType:"check"			//选择类型（多选、单选）
    	},
		title:"组织结构",      //弹出框标题
		okCallback:null,		//确认-回调函数
		cancelCallback:null,    //取消-回调函数
		beforeOkCallback:null,   //确认前-回调函数
		beforeSearch:null,        //请求前-回调函数
		echoDepartId:null,     //弹出后回显组织机构id
		requestParams:null, 		//请求参数json
		
    };
    
    //如果用户输入参数，将参数扩展
    if (opt && $.isPlainObject(opt)) {
        $.extend(this.opt, opt);
    }
    
    //给函数定义变量，并和opt对象一起传入原型
    
    this.params = null;
    this.departData = null;
 
    this.checkedIds = null;
    this.checkedAssets = null;
    //新增
    this.treeNodes = null;
    this.treeObj = null;
    //新增结束
    this.body = $("body");
    this.dialog = $("<div class='modal  modal-tahoe staff-selection' tabindex='-1'></div>");
};
var chooseType="";//声明一个全局单选还是多选按钮的变量
//原型中定义函数
DepartDialog.prototype = {
		
    show:function() {
        //1.this指的就是该原型对象
        //2.this.xxx表示原型对象调用函数中的变量
        var _this_ = this,
            opt = this.opt,
            body = this.body,
            dialog = this.dialog;
            chooseType=opt.params.chooseType;//显示的时候加载传过来的按钮值
        
        var timestamp = new Date().getTime();
        var dialog_id = "asset_modal_"+timestamp;
        dialog.attr("id",dialog_id);
        
        body.append(dialog); 
        
        dialog.load(ctx+"/assetDialog/departDialog.html",function(){
        	_this_.renderDialog();
			dialog.modal("show");
    	});
    },
    bindEvent:function(){
    	 var _this_ = this,
         opt = this.opt,
         body = this.body,
         dialog = this.dialog;
    	 
    	 var okBtn = dialog.find("button[data-id='ok']");
         var cancelBtn = dialog.find("button[data-id='cancel']");
         var closeBtn = dialog.find("button[data-id='close']");
         var clearBtn = dialog.find("button[data-id='clear']");
         var searchIpt = dialog.find("input[data-id='searchIpt']");
         var searchBtn = dialog.find("button[data-id='searchBtn']");
  
         
        //确认点击事件
        var isBindClick = _this_.isBindClick(cancelBtn);
 	    if(!isBindClick){
 	       $(okBtn).click(function(event){
 	 			_this_.ok();
 	 		});
 	    }
 	    
        //取消点击事件
        var isBindClick = _this_.isBindClick(cancelBtn);
	    if(!isBindClick){
	        $(cancelBtn).click(function(event){
	 			_this_.cancel();
	 		});
	    }
         
        //关闭点击事件
        var isBindClick = _this_.isBindClick(closeBtn);
	    if(!isBindClick){
	        $(closeBtn).click(function(event){
	 			_this_.cancel();
	 		});
        }
        
        //清空点击事件
        var isBindClick = _this_.isBindClick(clearBtn);
        if(!isBindClick){
	        $(clearBtn).click(function(event){
	 			$(searchIpt).val("");
	 			// _this_.doPage(1);
	 		});
        }
        
        var isBindClick = _this_.isBindClick(searchBtn);
        if(!isBindClick){
        	//搜索点击事件
            $(searchBtn).click(function(event){
            	_this_.doPage(1);
            });
        }

    },
    renderDialog:function(){
    	 var _this_ = this,
         opt = this.opt,
         body = this.body,
         dialog = this.dialog;
    	 //显示树菜单
    	 var timestamp = new Date().getTime();
    	 var treeContainer = dialog.find("div[data-id='tree']");
      	  $(treeContainer).attr("id","category_tree_"+timestamp);
      	  var treeSetting = {
    		view : {
    			showIcon : true
    		},
    		data : {
    			simpleData : {
    				enable : true,
    				idKey : "id",
    				pIdKey : "pId"
    			}
    		},
    		check: {
    			enable:false
    		},
    	    callback : {
    	        // 单击左侧事件
    	    	beforeClick : _this_.zTreeOnClick
    	    }
    	 };
    	
    	_this_.getTreeNodes();
    	_this_.treeObj = $.fn.zTree.init(treeContainer, treeSetting, _this_.treeNodes);
    	
    	if(!!opt.echoDepartId){
    		var currentNode = _this_.treeObj.getNodeByParam("id",opt.echoDepartId);  
    		_this_.treeObj.selectNode(currentNode,true,true);  
    	}
    	 //显示树菜单结束
		 _this_.bindEvent();
    },
    zTreeOnClick:function(treeId, treeNode, clickFlag){
    	var _this_ = this,
        opt = this.opt,
        body = this.body,
        dialog = this.dialog;
    	//根据部门id获取子节点信息
    	 $.ajax({
 			url : ctx + "/common/asset/getDepartSubnodeList",
 			type : "post",
 			dataType : "json",
 			data:{
 				"sid":treeNode.id
 			},
 			async : false,
 			success : function(result) {
 				if (result.success) {
 					///////////
 					 var boxIpt = ("input[data-id='box']");
 			    	 var departTbody = ("tbody[data-id='departTbody']");
 			    	 var departTbodyTemplate = null;	    
 			    	 if(chooseType == "check"){
 			    		departTbodyTemplate = $.templates("#departTbodyTemplate");
 			    		  $(boxIpt).click(function(){
 			    			  if (this.checked) {
 			    				  $("input[name='depart']").prop('checked', true);
 			    			    } else {
 			    			    	$("input[name='depart']").prop('checked', false);
 			    			    }
 			    		  });
 			    	 }else if(chooseType == "radio"){
 			    		$(boxIpt).remove();
 			    		departTbodyTemplate = $.templates("#departTbodyRadioTemplate");
 			    	 }else{
 			    		departTbodyTemplate = $.templates("#departTbodyTemplate");
 			    	 }
 					////////////
 			    	_this_.departData=result.departArrayList;
 					var assetOutput = departTbodyTemplate.render(result.departArrayList);
 					$(departTbody).html(assetOutput);
 				}
 			},
 			error : function() {
 				console.info("getAssetJson error");
 			},
 			complete : function() {
 			}
 		});
    	
    },
    getTreeNodes:function(){
    	var _this_ = this,
        opt = this.opt,
        body = this.body,
        dialog = this.dialog;
    	
    	if(!this.treeNodes || this.treeNodes.length <= 0){
    		var reqData = {};
    		if(!!opt.requestParams){
    			reqData = opt.requestParams
    		}
    		
    		$.ajax({
    			url : ctx + _this_.opt.url,
    			type : "post",
    			dataType : "json",
    			async : false,
    			data:_this_.opt.params,
    			success : function(result) {
    				if (result.success) {
    					_this_.treeNodes = result.departJsonArray;
    				}
    			},
    			error : function() {
    				console.info("getDepartJson error");
    			},
    			complete : function() {
    			}
    		});
    	}
    },
    doPage:function(pageNo){
    	 var _this_ = this,
         opt = this.opt,
         body = this.body,
         dialog = this.dialog;
    	 
    	 var searchIpt = dialog.find("input[data-id='searchIpt']");
    	 var searchVal = searchIpt.val();
    	 if(searchVal==""){
    		 alert("搜索条件不能为空");
    		 return;
    	 }
    	 //根据名称获取到数据
    	 $.ajax({
  			url : ctx + "/common/asset/getDepartByNameList",
  			type : "post",
  			dataType : "json",
  			data:{
  				"name":searchVal
  			},
  			async : false,
  			success : function(result) {
  				if (result.success) {
  					///////////
					 var boxIpt = ("input[data-id='box']");
			    	 var departTbody = ("tbody[data-id='departTbody']");
			    	 var departTbodyTemplate = null;	    
			    	 if(chooseType == "check"){
			    		departTbodyTemplate = $.templates("#departTbodyTemplate");
			    		  $(boxIpt).click(function(){
			    			  if (this.checked) {
			    				  $("input[name='depart']").prop('checked', true);
			    			    } else {
			    			    	$("input[name='depart']").prop('checked', false);
			    			    }
			    		  });
			    	 }else if(chooseType == "radio"){
			    		$(boxIpt).remove();
			    		departTbodyTemplate = $.templates("#departTbodyRadioTemplate");
			    	 }else{
			    		departTbodyTemplate = $.templates("#departTbodyTemplate");
			    	 }
					////////////
  					
  					//显示右侧数据
  					//var departTbody = ("tbody[data-id='departTbody']");
  			    	//var departTbodyTemplate = $.templates("#departTbodyTemplate");
  					var assetOutput = departTbodyTemplate.render(result.departArrayList);
  					$(departTbody).html(assetOutput);
  				}
  			},
  			error : function() {
  				console.info("getAssetJson error");
  			},
  			complete : function() {
  			}
  		});
    	 
    	 
    	 if(opt.beforeSearch){
    		 opt.beforeSearch();
    	 }
    	 //_this_.renderDialog();
    },
    getSelectedNodes:function(){
    	var _this_ = this,
        opt = this.opt,
        body = this.body,
        dialog = this.dialog;
    	
    	var nodes = _this_.treeObj.getSelectedNodes();
    	if(nodes!=null&& nodes.length>0){
    		_this_.selectNode = nodes[0];
    		console.log("category_id:"+_this_.selectNode.id +"----category_name:"+_this_.selectNode.name);
    	}
    	
    	return _this_.selectNode;
    },
    getCheckedAsset:function(){
    	var _this_ = this,
        opt = this.opt,
        body = this.body,
        dialog = this.dialog;
    	
    	var result = {};
    	var checkedValId = "";
    	var checkedValName = "";
    	dialog.find("input[name='depart']:checked").each(function () {
    			var departNameId = $(this).val();
    			checkedValId += "," + departNameId.split("_")[0];
    			checkedValName+= "," + departNameId.split("_")[1];
    	        
    	});
	    if (checkedValId.length > 0) {
	    	checkedValId = checkedValId.substring(1);
	    }
	    if (checkedValName.length > 0) {
	    	checkedValName = checkedValName.substring(1);
	    }
	    result.checkedIds = checkedValId;
	    result.checkedNames = checkedValName;
	    return result;
    },
    isBindClick:function(el){
    	var objEvt = $._data($(el)[0], 'events');
        if (objEvt && objEvt['click']) {
        	return true;
        } else {
        	return false;
        }
    },
    //关闭弹出框
    close: function() {
        this.dialog.modal("hide");
        $(this.dialog).remove();
    },
    ok:function() {
    	var _this_ = this,
        opt = this.opt,
        body = this.body,
        dialog = this.dialog;
    	
    	var result = _this_.getCheckedAsset();
    	console.log("checked result:",result);
    	//获取右侧单选按钮的数据
    	if(result.checkedIds==""){
    		alert("请选择一条组织机构");
    		return;
    	}
    	//获取左侧菜单数据的id和name
    	var selectNode = _this_.getSelectedNodes();
    	var selectNodeId="";
    	if(selectNode!=undefined){
    		selectNodeId=selectNode.id;
    	}
        //确认结果数据
        var item = {
        	 departId:selectNodeId,
        	 sId:result.checkedIds,
        	 fdName:result.checkedNames
        }
        
        if(opt.beforeOkCallback){
        	var isValid = opt.beforeOkCallback(item);
        	if(!isValid){
        		return;
        	}
        }
        //回显的数据 
        if(selectNodeId!=""){
        	 opt.echoDepartId=selectNodeId;
        }
      
    	_this_.close();
        
    	if(opt.okCallback){
    		opt.okCallback(item);
    	}
    },
    cancel:function() {
    	var _this_ = this,
    	opt = this.opt,
    	body = this.body,
    	dialog = this.dialog;
    	
    	_this_.close();
    	
    	if(opt.cancelCallback){
    		opt.cancelCallback();
    	}
    }
};


//显示组织机构弹框
var departDialog = null;
function showDepartDialog() {
	if(departDialog==null){
		departDialog = new DepartDialog({
			url:"/common/asset/getDepartGroup",//左侧菜单路径
			params:{
				state:1, //1 默认查询所有组织机构  2 查询自己部门的组织机构
				chooseType:"check" //check 多选 radio 单选
			},
			title:"组织结构",      //弹出框标题
			okCallback:function(item){
				//点击确定后的返回方法
				$("#sId").val(item.sId);
				$("#nameTree").val(item.fdName);
			},
			cancelCallback:function(){
				//console.log("cancel-callback");
			}, 
			beforeOkCallback:function(item){
				return true;
			}
	    });
	}
	departDialog.show();
}